﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using LocalService = Sunboxsoft.ASMS.Client.Domain.LocalService;
using Sunboxsoft.Common;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Package
{
    public partial class CheckoutPackagePurchaseBillView : UserControl, IView
    {
        #region Property
        WebRef.VPackagePurchaseBill _bill;
        Guid _billId;
        List<WebRef.EPayRecord> list = new List<WebRef.EPayRecord>();
        Promise _promise = new Promise();
        #endregion

        public CheckoutPackagePurchaseBillView(Guid billId)
        {
            InitializeComponent();
            _billId = billId;
        }

        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("checkout", Resources.isSettling, "收银", OnCheckedOut_Click))
                .AddAction(new ActionNode("cancel", Resources.isBack, "取消", OnCancelActionClick));
        }
        public void Active(ViewActiveArgs args)
        {
            _promise.Then(BindPayChannel)
                .Then(LoadPackagePurchaseBillDetail)
           .Run(null);
        }
        public void Resume(ViewResumeArgs args)
        {

        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("套餐购买单收银");
        }
        #endregion

        #region methods
        /// <summary>
        /// 绑定套餐购买单详细信息
        /// </summary>
        private void LoadPackagePurchaseBillDetail()
        {
            UIContext.Current.InvokeAsync(() =>
            {
                SingleResult<WebRef.VPackagePurchaseBill> result = new Service.GetService().GetPackagePurchaseBill(_billId);
                this.BeginInvoke(new Action<SingleResult<WebRef.VPackagePurchaseBill>>((p) =>
                {
                    if (p.IsSuccess)
                    {
                        _bill = p.Data;
                        this.ctlEditNumber.Text = p.Data.Id.ToString();
                        this.ctlEditCustomer.Text = string.Format("{0}-{1}", p.Data.CustomerName, p.Data.CustomerTelephone);
                        this.ctlEditSalesManager.Text = p.Data.SalesManagerName;
                        this.ctlEditPackage.Text = p.Data.PackageName;
                        this.ctlEditExpiringDate.Text = p.Data.PackageExpiringDate.ToString();
                        this.ctlEditChannel.Text = p.Data.BoughtChannelName;
                        this.ctlEditMarketPrice.Text = p.Data.PackageMarketPrice.ToString();
                        this.txtSalesCom.Text = p.Data.SalesCommissionAmount.ToString();
                        this.ctlEditPrice.Text = p.Data.BoughtPrice.ToString();
                        this.ctlEditMemo.Text = p.Data.Memo;
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(p.Message);
                        _promise.Resolve();
                    }
                }), result);
            });
        }
        /// <summary>
        /// 绑定收银渠道
        /// </summary>
        private void BindPayChannel()
        {
            UIContext.Current.InvokeAsync(() =>
            {
                ListResult<WebRef.EMasterDataItem> result = new LocalService.QueryService().QueryMasterDataItemList(Domain.Constant.MasterDataCodes.PayChannel, null, null);
                this.BeginInvoke(new Action<ListResult<WebRef.EMasterDataItem>>((p) =>
                {
                    if (p.IsSuccess)
                    {
                        ctlLookUpPayChannel.Properties.DataSource = p.Data.Items;
                        ctlLookUpPayChannel.Properties.DisplayMember = "Name";
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(p.Message);
                        _promise.Resolve();
                    }
                }), result);
            });
        }
        /// <summary>
        /// 数据检查
        /// </summary>
        /// <returns></returns>
        private bool ValidateData()
        {
            if (list.Count == 0)
            {
                UIContext.Current.ViewManager.ShowWarning("请选择收银渠道！");
                return false;
            }
            if (GetListPayRecord() == null)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获取添加的收银渠道
        /// </summary>
        /// <returns></returns>
        private List<WebRef.EPayRecord> GetListPayRecord()
        {
            List<WebRef.EPayRecord> listItem = new List<WebRef.EPayRecord>();
            for (int i = 0; i < this.ctlGridViewPay.RowCount; i++)
            {
                WebRef.EPayRecord Item = this.ctlGridViewPay.GetRow(i) as WebRef.EPayRecord;
                if (Item.PayAmount <= 0)
                {
                    UIContext.Current.ViewManager.ShowWarning("金额应大于0！");
                    return null;
                }
                listItem.Add(Item);
            }
            return listItem;
        }
        /// <summary>
        /// 收银
        /// </summary>
        private void CheckedOutPackageBill()
        {
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                ServiceResult result = new Service.CheckOutService().CheckOutPackagePurchaseBill(_billId, null, GetListPayRecord().ToArray<WebRef.EPayRecord>());
                this.BeginInvoke(new Action<ServiceResult>((p) =>
                {
                    this.HideMask();
                    if (p.IsSuccess)
                    {
                        UIContext.Current.ViewManager.CloseView(true, null);
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(p.Message);
                    }
                }), result);
            });
        }
        #endregion

        #region actions
        /// <summary>
        /// 收银
        /// </summary>
        private void OnCheckedOut_Click(object sender, object e)
        {
            if (ValidateData())
            {
                CheckedOutPackageBill();
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnCancelActionClick(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(true, null);
        }
        /// <summary>
        /// 添加收银渠道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlBtnAdd_Click(object sender, EventArgs e)
        {
            WebRef.EMasterDataItem emdItem = ctlLookUpPayChannel.EditValue as WebRef.EMasterDataItem;
            if (emdItem != null)
            {
                WebRef.EPayRecord item = new WebRef.EPayRecord(emdItem.Code, emdItem.Name, 0, "");
                item.BillId = _bill.Id;
                list.Add(item);
                this.ctlGridPay.DataSource = null;
                this.ctlGridPay.DataSource = list;
            }
        }
        /// <summary>
        /// 移除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RIButtonEditRemove_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Caption == "移除")
            {
                if (this.ctlGridViewPay.FocusedRowHandle > -1)
                {
                    WebRef.EPayRecord item = this.ctlGridViewPay.GetFocusedRow() as WebRef.EPayRecord;
                    list.Remove(item);
                    if (list.Count == 0)
                    {
                        this.ctlGridPay.DataSource = null;
                    }
                    else
                    {
                        this.ctlGridPay.DataSource = null;
                        this.ctlGridPay.DataSource = list;
                    }
                }
            }
        }
        #endregion
    }
}
